package datatypes;

import java.io.UnsupportedEncodingException;

import tools.ArrayMerge;

/**
 * Simple class which handles some String over network functions.
 * This file contains logic which is repeated for multiple send-commands.
 */
public final class MCString {
	/**
	 * Returns the same as MCString.tobytes, but with the string length
	 * as a short, added before the actual string.
	 * @param str
	 * @return
	 * @TODO Assert maximum string length.
	 */
	public static byte[] toBytesWithLength(String str) {
		byte[] bytestr = MCString.toBytes(str);
		
		//(length / 2) because utf16 uses 2 bytes to decode strings
		int length = bytestr.length / 2;

		byte[] lengthraw = new byte[2];
		lengthraw[0] = (byte)((length >> 8) & 0xff);
		lengthraw[1] = (byte)(length & 0xff);

		return ArrayMerge.mergeBytes(lengthraw, bytestr);
	}
	
	/**
	 * Converts the String into a set of bytes. The correct encoding is used.
	 * No catch-able exception is thrown when the Big Endian encoding can not be applied.
	 * The server will then crash, however all systems should support the encoding anyway!
	 * 
	 * @param str
	 * @return
	 */
	public static byte[] toBytes(String str) {
		try {
			//TODO: Check if the compiler treats this as a hardcoded string :)
			return str.getBytes("UTF-16BE");
			
		} catch (UnsupportedEncodingException e) {
			//in case Java can not encode this, we are all wrong. Don't
			throw new RuntimeException();
		}
	}
	
	
	
	public static String fromBytes(byte[] bytes) {
		try {
			return new String(bytes, "UTF-16BE");
			
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException();
		}
	}

}
